package com.hutao.sso.controller;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.font.GlyphVector;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hutao.sso.util.ExceptionUtil;
import com.hutao.sso.util.Result;
import com.hutao.sso.util.TmFileUtil;

@RequestMapping("/fileCache")
@Controller
public class FileCacheController {
	private Logger log = LoggerFactory.getLogger(FileCacheController.class);

	@Value("${config.resource.pic.url}")
	private String resourcePicUrl;

	@Value("${mark.pic.temp.path}")
	private String markPicTempPath;
	
	@Value("${config.local.pic.url}")
	private String localPicUrl;

	/**
	 * 图片加水印 1.缓存中有水印图片从缓存文件中读取 2.缓存中没有水印图片,先缓存中生成文件,在读取
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@PostMapping("/seekMarkPicUrl")
	@ResponseBody
	public Result seekMarkPicUrl(@RequestParam(value = "fileName", required = true) String fileName,
			@RequestParam(value = "secret", required = true) String secret,
			@RequestParam(value = "signature", required = true) String signature, HttpServletRequest request,
			HttpServletResponse response) {
		//InputStream in = null;
		OutputStream os = null;

		try {
			String fileType = "";
			signature = URLDecoder.decode(signature, "UTF-8");
			
			System.out.println(signature);
			

			if (StringUtils.isNotBlank(fileName) && fileName.indexOf(".") != -1) {
				fileType = fileName.substring(fileName.indexOf("."));
			} else {
				log.warn("--------------fileName文件格式不正确或者为空!--------------------");
				return new Result(false, "fileName文件格式不正确或者为空!");
			}

			// 没有文件夹创建文件夹
			TmFileUtil.createFloder(markPicTempPath);
			File markPicTempFile = new File(markPicTempPath + "/" + secret + fileType);

			if (markPicTempFile.exists()) {
				return new Result(true, "读取水印图片成功!", resourcePicUrl + "temp/" + secret + fileType);
			}

			//in = download(resourcePicUrl + fileName);

			Image src = ImageIO.read(new File(localPicUrl+fileName));

			// 图片宽度
			int width = src.getWidth(null);
			// 图片高度
			int height = src.getHeight(null);

			BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

			Graphics2D g2d = image.createGraphics();
			// 绘原图
			g2d.drawImage(src, 0, 0, width, height, null);
			// 比例
			g2d.scale(1, 1);

			g2d.addRenderingHints(
					new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
			g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

			// 颜色
			Color color = Color.decode("#29944f");

			// 字体
			Font font = new Font("宋体", Font.PLAIN, 80);

			GlyphVector fontGV = font.createGlyphVector(g2d.getFontRenderContext(), signature);
			Rectangle size = fontGV.getPixelBounds(g2d.getFontRenderContext(), 0, 0);
			Shape textShape = fontGV.getOutline();
			double textWidth = size.getWidth();
			double textHeight = size.getHeight();
			AffineTransform rotate45 = AffineTransform.getRotateInstance(Math.PI / 4d);
			Shape rotatedText = rotate45.createTransformedShape(textShape);
			// use a gradient that repeats 4 times
			g2d.setPaint(new GradientPaint(0, 0, color, image.getWidth() / 2, image.getHeight() / 2, color));

			// 透明度
			// g2d.setStroke(new BasicStroke(alpha));
			g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.1f));// 1.0f为透明度
																						// ，值从0-1.0，依次变得不透明
			// step in y direction is calc'ed using pythagoras + 5 pixel padding
			double yStep = Math.sqrt(textWidth * textWidth / 2) + 250;
			// step over image rendering watermark text
			for (double x = -textHeight * 3; x < image.getWidth(); x += (textHeight * 3)) {
				double y = -yStep;
				for (; y < image.getHeight(); y += yStep) {
					g2d.draw(rotatedText);
					boolean carelessness = true;
					if (carelessness)// 字体实心
					{
						g2d.fill(rotatedText);
					}
					g2d.translate(0, yStep);
				}
				g2d.translate(textHeight * 6, -(y + yStep));
			}

			g2d.dispose();

			// 没有文件创建文件
			if (!markPicTempFile.exists()) {
				markPicTempFile.createNewFile();
			}

			// 输出水印文件到临时文件
			os = new FileOutputStream(markPicTempFile);
			// 生成图片
			ImageIO.write(image, "JPG", os);

			return new Result(true, "读取水印图片成功!", resourcePicUrl + "temp/" + secret + fileType);

		} catch (Exception e) {
			log.error("---------读取水印图片失败!----------" + ExceptionUtil.getStackTrace(e));
			e.printStackTrace();
			return new Result(false, "读取水印图片失败!");
		} finally {
			if (null != os) {
				try {
					os.close();
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		}
	}

	// /**
	// * 图片加水印
	// * 1.缓存中有水印图片从缓存文件中读取
	// * 2.缓存中没有水印图片,先缓存中生成文件,在读取
	// *
	// * @param request
	// * @param response
	// * @return
	// */
	// @PostMapping("/seekMarkPicUrl")
	// @ResponseBody
	// public Result seekMarkPicUrl(@RequestParam(value = "fileName", required =
	// true) String fileName,
	// @RequestParam(value = "secret", required = true) String secret,
	// @RequestParam(value = "signature", required = true) String signature,
	// HttpServletRequest request, HttpServletResponse response) {
	// InputStream in = null;
	// OutputStream os = null;
	//
	// try {
	// String fileType = "";
	// signature = URLDecoder.decode(signature, "UTF-8");
	//
	// if (StringUtils.isNotBlank(fileName) && fileName.indexOf(".") != -1) {
	// fileType = fileName.substring(fileName.indexOf("."));
	// } else {
	// log.warn("--------------fileName文件格式不正确或者为空!--------------------");
	// return new Result(false, "fileName文件格式不正确或者为空!");
	// }
	//
	// //没有文件夹创建文件夹
	// TmFileUtil.createFloder(markPicTempPath);
	// File markPicTempFile = new File(markPicTempPath + "/" + secret +
	// fileType);
	//
	// if (markPicTempFile.exists()) {
	// return new Result(true, "读取水印图片成功!", resourcePicUrl + "temp/" + secret +
	// fileType);
	// }
	//
	// in = download(resourcePicUrl + fileName);
	//
	// double degree = 45;
	// Image srcImg = ImageIO.read(in);
	// BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null),
	// srcImg.getHeight(null),
	// BufferedImage.TYPE_INT_RGB);
	// Graphics2D graphics = buffImg.createGraphics();
	// graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
	// RenderingHints.VALUE_INTERPOLATION_BILINEAR);
	// graphics.drawImage(
	// srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null),
	// Image.SCALE_SMOOTH), 0, 0,
	// null);
	//
	// if (degree > 0) {
	// graphics.rotate(Math.toRadians(degree), (double) buffImg.getWidth() / 2,
	// (double) buffImg.getHeight() / 2);
	// }
	//
	// graphics.setColor(Color.RED);
	// graphics.setFont(new Font("宋体", Font.BOLD, 75));
	// float alpha = 0.5f;
	// graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
	// alpha));
	// //graphics.drawString(signature, buffImg.getWidth() / 2,
	// buffImg.getHeight() / 2);
	// System.out.println( buffImg.getWidth()+"----"+buffImg.getHeight());
	// graphics.drawString(signature,
	// buffImg.getWidth()/2,buffImg.getHeight()/2);
	// graphics.dispose();
	//
	// //没有文件创建文件
	// if (!markPicTempFile.exists()) {
	// markPicTempFile.createNewFile();
	// }
	//
	// //输出水印文件到临时文件
	// os = new FileOutputStream(markPicTempFile);
	// // 生成图片
	// ImageIO.write(buffImg, "JPG", os);
	//
	// return new Result(true, "读取水印图片成功!", resourcePicUrl + "temp/" + secret +
	// fileType);
	//
	// } catch (Exception e) {
	// log.error("---------读取水印图片失败!----------" +
	// ExceptionUtil.getStackTrace(e));
	// e.printStackTrace();
	// return new Result(false, "读取水印图片失败!");
	// } finally {
	// if(null != in) {
	// try {
	// in.close();
	// } catch (IOException e) {
	// e.printStackTrace();
	// }
	// }
	// if(null != os) {
	// try {
	// os.close();
	// } catch (Exception e2) {
	// e2.printStackTrace();
	// }
	// }
	// }
	// }

	/**
	 * 根据图片url下载文件至本地
	 * 
	 * @param urlString
	 * @param savePath
	 * @param fileName
	 * @throws Exception
	 */
	public InputStream download(String urlString) throws Exception {
		// 构造URL
		URL url = new URL(urlString);
		// 打开连接
		URLConnection con = url.openConnection();
		// 设置请求超时为5s
		con.setConnectTimeout(5 * 1000);
		// 输入流
		InputStream is = con.getInputStream();
		return is;
	}

}
